package us.kg.kotoriforest.schedule.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import us.kg.kotoriforest.schedule.common.Result;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 前后端通信工具类
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/11
 */
public final class WebUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private WebUtil() {
    }

    /**
     * 向前端响应 JSON 串
     *
     * @param response servlet 中请求对应的响应对象
     * @param result   JSON 串的实体类
     * @param <T>      result 类中 data 的类型
     */
    public static <T> void respondJSON(HttpServletResponse response, Result<T> result) {
        response.setContentType("application/json;charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            String JSON = MAPPER.writeValueAsString(result);
            writer.write(JSON);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T receiveJSON(HttpServletRequest request, Class<T> clazz) {
        T t = null;
        try (BufferedReader reader = request.getReader()) {
            StringBuilder buffer = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            t = MAPPER.readValue(buffer.toString(), clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
}
